--[[
范围技能：
技能1：直线，前方3格
技能2：方形，周围2格
技能3：圆形，周围2格
技能4：扇形，前方90°+3格
--]]

local skynet = require "skynet"
local scene_map = require "scene_map"
local common_def = require "common_def"
local s = require "service"
require "fight"

local M = {}

local function handle_skill1(player)
    local skill_id = 1
    skynet.error("handle skill 1, uid:" .. player:get_uid())
    local player_position = player:get_position()
    local direction = player_position.direction
    local target_player_ids = {}
    local ids = {}
    -- 获取前方3格玩家
    for i = 1, 3 do
        local x = player_position.x
        local y = player_position.y
        if direction == common_def.Direction.UP then
            y = y - i
        elseif direction == common_def.Direction.DOWN then
            y = y + i
        elseif direction == common_def.Direction.LEFT then
            x = x - i
        elseif direction == common_def.Direction.RIGHT then
            x = x + i
        end

        if y <= scene_map.max_y and y >= 0 and x <= scene_map.max_x and x >= 0 then
            ids = scene_map.get_player_ids_by_position(x, y)
            for _, uid in pairs(ids) do
                table.insert(target_player_ids, uid)
                -- target_player_ids[uid] = {x, y}
            end
        end
    end

    -- TODO: 额外处理target_player_ids
    s.fight.fight_obj(player:get_uid(), target_player_ids, skill_id)
end

local function handle_skill2(player)
    local skill_id = 2
    skynet.error("handle skill 2, uid:" .. player:get_uid())
    local player_position = player:get_position()
    local x = player_position.x
    local y = player_position.y

    local target_player_ids = {}
    local ids = {}

    local function insert_target_player_ids(target_x, target_y)
        ids = scene_map.get_player_ids_by_position(target_x, target_y)
        for _, uid in pairs(ids) do
            table.insert(target_player_ids, uid)
        end
    end

    for i = 1, 2 do
        x = player_position.x
        y = player_position.y

        insert_target_player_ids(x, y)
        insert_target_player_ids(x + i, y)
        insert_target_player_ids(x - i, y)
        insert_target_player_ids(x, y + i)
        insert_target_player_ids(x, y - i)
        insert_target_player_ids(x + i, y + i)
        insert_target_player_ids(x + i, y - i)
        insert_target_player_ids(x - i, y + i)
        insert_target_player_ids(x - i, y - i)
    end

    s.fight.fight_obj(player:get_uid(), target_player_ids, skill_id)
end

M.SKILL_ID2FUNC = {
    [1] = handle_skill1,
    [2] = handle_skill2,
}

function M.dispatch_skill(player, skill_id)
    local func = M.SKILL_ID2FUNC[skill_id]
    if func then
        func(player)
    else
        skynet.error("no skill id:" .. skill_id)
    end
end

return M